import { AppDataSource } from "../data-source";
import { NextFunction, Request, Response } from "express";
import { User } from "../entity/User";
import { Role } from "../entity/Role";

export class UserController {
  private userRespository = AppDataSource.getRepository(User);
  private roleRespository = AppDataSource.getRepository(Role);

  async save(request: Request, response: Response, next: NextFunction) {
    const { username, rolename } = request.body;
    const user = new User();
    user.username = username;
    const role = await this.roleRespository.findOne({
      where: { name: rolename },
    });
    user.roles = [role];
    await this.userRespository.save(user);
    response.json(user);
  }

  async one(request: Request, response: Response, next: NextFunction) {
    const id = request.params.id;
    const user = await this.userRespository.findOne({
      where: { id },
      relations: ["roles"],
    });
    response.json(user);
  }

  async all(request: Request, response: Response, next: NextFunction) {
    const users = await this.userRespository.find({
      relations: ["roles"],
    });
    response.json(users);
  }
}
